<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tab Communication B</title>
</head>
<body>
    <h1>Tab Communication B</h1>
    <script>
        // 注册Service Worker
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', () => {
                navigator.serviceWorker.register('service-worker.js')
                    .then((registration) => {
                        console.log('Service Worker registered with scope:', registration.scope);
                    })
                    .catch((error) => {
                        console.log('Service Worker registration failed:', error);
                    });
            });
        }

        const channel = new BroadcastChannel('tab-communication');
        channel.onmessage = (event) => {
            console.log('Received message via BroadcastChannel:', event.data);
        };

        // 监听来自Service Worker的消息
        navigator.serviceWorker.addEventListener('message', (event) => {
            console.log('Received message via Service Worker:', event.data);
        });

        // 监听localStorage变化
        window.addEventListener('storage', (event) => {
            if (event.key === 'sharedData') {
                console.log('sharedData changed:', event.newValue);
            }
        });
    </script>
</body>
</html>